import mss
import os
import sys
import threading
import PySimpleGUI as sg
from datetime import datetime
from pynput import keyboard


sg.theme("Default1")


def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

def send_hotkey_events(key):
    window.write_event_value(key, None)


def func():
    with keyboard.GlobalHotKeys({
            '<alt>+<ctrl>+s': lambda key='Capture': send_hotkey_events(key),
            '<alt>+<ctrl>+q': lambda key="QUIT": send_hotkey_events(key),
        }) as h:
        h.join()


def capture_screenshot(window, savedir, monitor_index=1, prefix="SCREENSHOT_HELPER"):
    os.makedirs(savedir, exist_ok=True)
    window.hide()
    screenshot_filename = os.path.join(
        savedir, f"{prefix}_{datetime.now().strftime('%Y%m%d%H%M%S')}_SCREEN.png")
    print(f"save screenshot to {screenshot_filename}")
    with mss.mss() as screen:
        screen.shot(mon=monitor_index, output=screenshot_filename)
    window.un_hide()


source_dir = os.path.join(os.getcwd(), "screenshots")

layout = [[
    sg.FolderBrowse('Set Folder', size=(15, 3), initial_folder=source_dir, target='--WS--'),
    sg.Button('Capture', size=(15, 3)),
    sg.Button('QUIT', size=(15, 3))
]]

layout.append([
        [sg.Text(f"Hotkey: ", size=(6, 1)), 
            sg.Text("SHOT: CTL + ALT + S ", font=('Mono', 9), text_color="#DDDDDD", background_color="#27AE60"),
            sg.Text("QUIT: CTL + ALT + Q ", font=('Mono', 9), text_color="#DDDDDD", background_color="#CB4335")],
        [sg.Text(f"Folder: ", size=(6, 1)), 
            sg.Input(source_dir, size=(45, 1), key="--WS--", readonly=True)],
        [sg.Text(f"Prefix: ", size=(6, 1)), 
            sg.Input("SCREENSHOT_HELPER", size = (45, 1), key = "--PREFIX--")]
    ])

multi_mintors = False
with mss.mss() as screen:
    if (len(screen.monitors) - 1) == 2:
        multi_mintors = True
        layout.append([[sg.Text(f"Monitor: ", size=(6, 1)),
                        sg.Radio("1st", "MONITOR", default=True,
                                 key="--MONITOR--"),
                        sg.Radio("2nd", "MONITOR", default=False)]])

window = sg.Window("Screenshot Helper", layout=layout, icon=resource_path("logo.ico"))
# window.hide()
threading.Thread(target=func, daemon=True).start()

while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, 'QUIT'):
        break
    elif event == 'Capture':
        if multi_mintors:
            monitor_index = 1 if values['--MONITOR--'] else 2
        else:
            monitor_index = 1
        threading.Thread(
            target=capture_screenshot,
            args=(window, values['--WS--'], monitor_index, values['--PREFIX--']),
            daemon=True
        ).start()

window.close()
